<?php
header("Content-Type:text/html;charset=utf-8");
ob_start();
set_time_limit(0);
include("../../nncms_manager_inc.php");

include_once LOGIC_DIR . 'video' . DIRECTORY_SEPARATOR . 'vod_index.class.php';
include_once LOGIC_DIR . 'seekpoint' . DIRECTORY_SEPARATOR . 'seekpoint.class.php';

//导入语言包
 if (isset($_POST["language_dir"]))
 {
 	$language_dir=$_POST["language_dir"];
 }
include $nncms_config_path . "nn_cms_manager/languages/" . $language_dir . "/language.php";

$org_id = $_POST["nns_org_id"];
$org_type = $_POST["nns_org_type"];

$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken)
{
	try
	{
		$state = file_import_to_txt($_FILES['Filedata']['tmp_name']);
		echo $state;
	}
	catch (Exception $e)
	{
		echo 'csv文件格式错误';
	}
}

/**
 * 将要删除的数据整理好放入txt文件中，给计划任务备用
 * @param string $upload_file 上传文件路径
 * @param string $sp_id SP ID
 * @param string $file_path txt文件路径
 * @return string
 * @author chunyang.shu
 * @date 2015-03-02
 */
function file_import_to_txt($upload_file)
{
	$upload_file = fopen($upload_file, 'r');
 	$dc = nl_get_dc(array (
 			'db_policy' => NL_DB_WRITE,
 	));
 	$dc->open();
 	$str_filed = "nns_id,nns_index";
 	$str_error="";
 	$i=0;
 	while (!feof($upload_file))
 	{
 		$i++;
 		$line_arr = fgetcsv($upload_file);
 		if(empty($line_arr))
 		{
 			break;
 		}
 		$import_id = empty($line_arr[4]) ? null : $line_arr[4];
 		$result=nl_vod_index::get_index_info_by_import_id($dc, $import_id,$str_filed,'mgtv');
 		if($result === false)
 		{
 			$str_error.="第{$i}行 query import id db error <br/>";
 			continue;
 		}
 		else if($result === true)
 		{
 			$str_error.="第{$i}行 no query import id data <br/>";
 			continue;
 		}
 		
 		$array =array();
 		$array['nns_name'] = (strlen($line_arr[0]) <=0 ) ? "" : $line_arr[0];
 		$line_arr[1] = empty($line_arr[1]) ? "0" : $line_arr[1];
 		switch ($line_arr[1])
 		{
 			case '1':
 				$array['nns_type'] = '1';
 				break;
 			case '2':
 				$array['nns_type'] = '2';
 				break;
 			default:
 				$array['nns_type'] = '0';
 		}
 		$array['nns_image'] = '';
 		$array['nns_begin'] = empty($line_arr[3]) ? "0" : $line_arr[3];
 		$array['nns_end'] = '0';
 		foreach ($result as $val)
 		{
 			$array['nns_video_id'] = $val['nns_id'];
 			$array['nns_video_index'] = $val['nns_index'];
 			$result_query=nl_seekpoint::_select_data($dc, array_filter($array));
 			if($result_query === false)
 			{
 				$str_error.="-----第{$i}行 query import id db error <br/>";
 				continue;
 			}
 			else if($result_query === 2)
 			{
 				$str_error.="-----第{$i}行 query import id data exsit <br/>";
 				continue;
 			}
 			$result_add=nl_seekpoint::add_seekpoint($dc, $array);
 			if($result_add === false)
 			{
 				$str_error.="-----第{$i}行 add seekpoint db error <br/>";
 				continue;
 			}
 		}
 	}
 	fclose($upload_file);
 	return $str_error;
}
